package club.vann.kafka.mock.service.acceptor;

import com.cyberx.lunyu.AcceptorOuterClass;
import java.util.EnumMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AcceptorServiceFactory implements ApplicationContextAware {
  private final EnumMap<AcceptorOuterClass.Acceptor.RequestType, AcceptorService> requestMapping =
      new EnumMap<>(AcceptorOuterClass.Acceptor.RequestType.class);

  public Optional<AcceptorService> getAcceptorService(
      AcceptorOuterClass.Acceptor.RequestType requestType) {
    return Optional.ofNullable(requestMapping.get(requestType));
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    Map<String, AcceptorService> maps = applicationContext.getBeansOfType(AcceptorService.class);
    maps.values()
        .forEach(
            acceptorService -> requestMapping.put(acceptorService.requestType(), acceptorService));
  }
}
